import React, { useCallback, useMemo, useState } from 'react';
import { Checkbox, Skeleton, Row, Space, Radio } from 'antd';
import { getFileTypeIconSvg } from '@inbiz/utils';
import './style.less';
import classNames from 'classnames';

const prefixCls = 'inbiz-cListCard';

const ListCardView = (props) => {
  const {
    keyName,
    dataSource = [],
    loading,
    value = [],
    onChange,
    renderTitle,
    renderDescription,
    hanleClick,
    getAvatarURL,
    multiple,
    isDoc,
    config,
  } = props;

  const { viewType, isSelected = false } = config;

  const getKeyValue = useCallback(
    (item) => (typeof keyName == 'function' ? keyName(item) : item[keyName]),
    [keyName],
  );
  const FormWrapper = useMemo(
    () => (multiple ? Checkbox.Group : Radio.Group),
    [multiple],
  );
  const FormItem = useMemo(() => (multiple ? Checkbox : Radio), [multiple]);
  const formValue = useMemo(
    () => (multiple ? value : value?.[0]),
    [value, multiple],
  );

  const [indeterminate, _indeterminate] = useState(true);
  const [checkedAll, _checkedAll] = useState(false);

  // 显示文件图标
  const thumbImg = useCallback(
    (row, source: string, isPureType?: boolean) => {
      let src, errorImg;
      if (isDoc) {
        if (row.folderType == 1) {
          src = getFileTypeIconSvg('.folder');
        } else if (row.fileType == 32) {
          if (row.shortcut?.entryType == 1) {
            src = getFileTypeIconSvg('.link-folder');
          } else {
            errorImg = getFileTypeIconSvg(row.shortcut?.entryName);
            src = `/Thumbnails/default/${row.shortcut.entryId}.jpg`;
            if (isPureType) {
              src = errorImg;
            }
          }
        } else if (row.fileType == 2) {
          errorImg = getFileTypeIconSvg(row.name);
          src = `/Thumbnails/default/${row.id}.jpg`;
          if (isPureType) {
            src = errorImg;
          }
        } else {
        }
      } else {
        src = source;
      }
      return (
        <img
          className={'list-card-doc-icon'}
          src={src}
          onError={(e: any) => {
            if (isPureType || !isDoc) {
              return;
            }
            if (e.target.getAttribute('loaded')) return;
            e.target.src = errorImg;
            e.target.setAttribute('loaded', true);
            e.target.classList.add('error');
          }}
        />
      );
    },
    [isDoc],
  );

  const onCheckAllChange = useCallback(
    (e) => {
      onChange?.(e.target.checked ? dataSource.map((v) => getKeyValue(v)) : []);
      _indeterminate(false);
      _checkedAll(e.target.checked);
    },
    [onChange, dataSource],
  );

  const handleChange = useCallback(
    (e) => {
      let keys = [];
      if (multiple) {
        keys = e;
      } else {
        keys = e.target.checked ? [e.target.value] : [];
      }
      onChange?.(keys);
      _indeterminate(!!keys.length && keys.length < dataSource.length);
      _checkedAll(keys.length === dataSource?.length);
    },
    [onChange, dataSource, multiple],
  );

  const renderItem = useCallback(
    (item, i) => {
      const checked = value?.includes?.(getKeyValue(item));
      return (
        <Skeleton loading={loading} active avatar key={i}>
          <div
            className={classNames('list-card-item', {
              checked: checked,
              large: item.fileType == 2,
            })}
            onClick={(e: any) => {
              let parentNode = e.target;
              while (parentNode) {
                if (parentNode == document) {
                  break;
                }
                if (
                  [...parentNode['classList']].indexOf('list-card-item') > -1
                ) {
                  parentNode
                    .querySelector(
                      multiple ? '.ant-checkbox-wrapper' : '.ant-radio-wrapper',
                    )
                    ?.click?.();
                  break;
                }
                parentNode = parentNode['parentNode'];
              }
            }}
          >
            {isSelected ? (
              <FormItem
                style={{
                  pointerEvents: 'none',
                  ...(checked
                    ? {
                        display: 'block',
                      }
                    : {}),
                }}
                value={getKeyValue(item)}
                checked={checked}
              />
            ) : null}
            <div className="list-card-thumb">
              {thumbImg?.(item, getAvatarURL?.(item))}
            </div>
            <div className="list-card-item-bottom">
              {isDoc && item.fileType == 2
                ? thumbImg?.(item, getAvatarURL?.(item), true)
                : null}{' '}
              {renderTitle?.(item)}
            </div>
          </div>
        </Skeleton>
      );
    },
    [
      isSelected,
      multiple,
      value,
      FormItem,
      getKeyValue,
      getAvatarURL,
      thumbImg,
      renderTitle,
    ],
  );

  const cardComponent = isDoc ? (
    <>
      <Row
        className="list-card-body"
        gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}
      >
        {dataSource.filter((item) => item.folderType == 1).map(renderItem)}
      </Row>
      <Row
        className="list-card-body"
        gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}
      >
        {dataSource.filter((item) => item.fileType == 2).map(renderItem)}
      </Row>
    </>
  ) : (
    <Row className="list-card-body" gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
      {dataSource.map(renderItem)}
    </Row>
  );

  return (
    <div className={`${prefixCls}`}>
      {isSelected && multiple ? (
        <div className="list-selection-row">
          <Space>
            <Checkbox
              indeterminate={indeterminate}
              onChange={onCheckAllChange}
              checked={checkedAll}
            ></Checkbox>
            <span>已选中 {value.length} 个文件/文件夹</span>
          </Space>
        </div>
      ) : null}
      {isSelected ? (
        <FormWrapper value={formValue} onChange={handleChange}>
          {cardComponent}
        </FormWrapper>
      ) : (
        cardComponent
      )}
    </div>
  );
};

export default ListCardView;
